package com.lagou;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;

/**
 * @Author : liuchangling
 * @Descrition :
 * @Date： Created in 5:18 下午 2021/11/15
 */
@Component
public class MyTomcat {
    public static void createTomcat() {
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(8081);
            File tempDir = createTempDir("tomcat");
            tomcat.addWebapp("/", tempDir.getAbsolutePath());
            tomcat.start();
            //因为tomcat.start()是非阻塞型的，所以要阻塞一下，不能让服务停止。
            tomcat.getServer().await();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (LifecycleException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static File createTempDir(String prefix) throws Exception {
        try {
            File tempDir = File.createTempFile(prefix + ".", "." + 8081);
            if (tempDir.exists()) {
                tempDir.delete();
            }
            tempDir.mkdir();
            return tempDir;
        } catch (IOException ex) {
            throw new Exception(ex);
        }
    }
}
